package services

import (
	"errors"
	"registration-booking/app/common/request"
	"registration-booking/app/models"
	"registration-booking/global"
	"strconv"
)

type cardService struct{}

var CardService = new(cardService)

// CreateCard 创建就诊卡
func (s *cardService) CreateCard(form request.Card, id string) (error, models.Card) {
	userId, _ := strconv.Atoi(id)
	number, err := models.FindCardByIdNumber(form.IdNumber)
	if err != nil {
		return err, models.Card{}
	}
	if len(number) != 0 {
		return errors.New("该身份证已创建就诊卡，请绑定~"), models.Card{}
	}
	card := models.Card{
		Name:         form.Name,
		IdType:       form.IdType,
		IdNumber:     form.IdNumber,
		Nation:       form.Nation,
		Relationship: form.Relationship,
		Phone:        form.Phone,
		Address:      form.Address,
	}
	if form.Default {
		// 取消其他默认就诊卡
		err := models.CancelAllCardDefaults(uint(userId))
		if err != nil {
			return err, models.Card{}
		}
	}
	if err := global.App.DB.Create(&card).Error; err != nil {
		return err, card
	}

	// 绑定就诊卡
	cardUser := models.CardUser{
		CardId:  card.ID.ID,
		UserId:  uint(userId),
		Default: form.Default,
	}
	err = cardUser.Create()
	if err != nil {
		return err, models.Card{}
	}
	return nil, card
}

// GetCardList 获取就诊卡列表
func (s *cardService) GetCardList(id string) (error, []models.Card) {
	var list []models.Card
	uid, err := strconv.Atoi(id)
	if err != nil {
		return err, nil
	}
	// 获得列表
	cardUsers, err := models.FindCardUserByUserId(uint(uid))
	if err != nil {
		return err, nil
	}
	for _, cardUser := range cardUsers {
		card, err := models.FindCardById(cardUser.CardId)
		if err != nil {
			return err, nil
		}
		card.Default = cardUser.Default
		list = append(list, card)
	}
	return nil, list
}

func (s *cardService) GetAllCardList(page request.Page) (error, int64, []models.Card) {

	query := ""
	if page.Query != "" {
		uid, err := strconv.Atoi(page.Query)
		if err != nil {
			return err, 0, nil
		}
		// 获得列表
		cardUsers, err := models.FindCardUserByUserId(uint(uid))
		if err != nil {
			return err, 0, nil
		}
		if len(cardUsers) > 0 {
			query = " and id in ("

			for i, cardUser := range cardUsers {
				if i == 0 {
					query += " " + strconv.Itoa(int(cardUser.CardId))
				} else {
					query += " ," + strconv.Itoa(int(cardUser.CardId))
				}
			}
			query += ")"
		} else {
			return nil, 0, make([]models.Card, 0)
		}

	}
	byPage, total, err := models.FindAllCardListByPage(page.PageNo, page.PageSize, query)
	if err != nil {
		return err, 0, nil
	}
	return nil, total, byPage
}

// GetCardById 获取就诊卡详情
func (s *cardService) GetCardById(id string) (error, models.Card) {
	cardId, err := strconv.Atoi(id)
	if err != nil {
		return err, models.Card{}
	}
	var card models.Card
	cardUser, err := models.FindCardUserByCardId(uint(cardId))
	if len(cardUser) == 0 || err != nil {
		return err, models.Card{}
	}
	if err := global.App.DB.First(&card, id).Error; err != nil {
		return err, card
	}
	card.Default = cardUser[0].Default
	return nil, card
}

// UpdateCard 更新就诊卡
func (s *cardService) UpdateCard(card models.Card, form request.Card) error {
	updateCard := request.UpdateCard{
		Id:           form.Id,
		Name:         form.Name,
		IdType:       form.IdType,
		Nation:       form.Nation,
		Relationship: form.Relationship,
		Phone:        form.Phone,
		Address:      form.Address,
		Default:      form.Default,
	}
	if err := global.App.DB.Model(&card).Updates(updateCard).Error; err != nil {
		return err
	}
	return nil
}

// DeleteCard 删除就诊卡
func (s *cardService) DeleteCard(id string) error {
	cardId, err := strconv.Atoi(id)
	if err != nil {
		return err
	}
	err = models.DeleteCardUserByCardId(uint(cardId))
	if err != nil {
		return err
	}
	//if err := global.App.DB.Delete(&models.Card{}, id).Error; err != nil {
	//	return err
	//}
	return nil
}

func (s *cardService) BindCard(form request.BindCard, id string) (error, models.CardUser) {
	userId, _ := strconv.Atoi(id)
	number, err := models.FindCardByIdNumber(form.IdNumber)
	if err != nil {
		return err, models.CardUser{}
	}
	if len(number) == 0 {
		return errors.New("该身份证未创建就诊卡，请先创建就诊卡~"), models.CardUser{}
	}

	// 查询是否已经绑定
	cardUser, err := models.FindCardUserByUserIdAndCardId(uint(userId), number[0].ID.ID)
	if err != nil {
		return err, models.CardUser{}
	}
	if len(cardUser) > 0 {
		return errors.New("已绑定该就诊卡~"), models.CardUser{}

	}
	card := models.CardUser{
		CardId: number[0].ID.ID,
		UserId: uint(userId),
	}
	err = card.Create()
	if err != nil {
		return err, models.CardUser{}
	}
	return nil, card
}
